//
//  VVideoClipManger.m
//  VChatVideoClip
//
//  Created by huangbolun on 2017/10/9.
//  Copyright © 2017年 huangbolun. All rights reserved.
//

#import "VVideoClipManger.h"

@implementation VVideoClipManger

+ (instancetype)shareClipManger{
    static VVideoClipManger *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [VVideoClipManger new];
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        //  设置视频的大小
        NSString *myPathDocs =  [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"mergeVideo-0.mov"]];

        instance.catchPath = myPathDocs;
    });
    return instance;
}

- (void)getVideoListWithCompelet:(void (^)(PHFetchResult *result))complete{
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status == PHAuthorizationStatusAuthorized) {
            PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeVideo options:nil];
            if (complete != nil) {
                complete(result);
            }
            NSLog(@"有权限");
        }else{
            NSLog(@"没有权限");
        }
    }];
}

- (UIImage*) getVideoPreViewImageWithAsset:(AVURLAsset *)asset second:(NSInteger)second
{
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    gen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(second, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *img = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    return img;
}

- (void)clipWithAssert:(AVAsset *)assert Begin:(NSInteger)begin end:(NSInteger)end compelet:(void (^)(NSURL *url))compelete{
    NSString *myPathDocs = self.catchPath;
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:myPathDocs]) {
        [[NSFileManager defaultManager] removeItemAtPath:myPathDocs error:nil];
    }
    
    
    NSURL *myUrl = [NSURL fileURLWithPath:myPathDocs];
    
    
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:assert presetName:AVAssetExportPresetHighestQuality];
    exportSession.outputURL = myUrl;
    exportSession.outputFileType = AVFileTypeQuickTimeMovie;
    exportSession.shouldOptimizeForNetworkUse = YES;
    exportSession.timeRange = CMTimeRangeMake(CMTimeMakeWithSeconds(begin,  1 *NSEC_PER_SEC), CMTimeMakeWithSeconds(end,  1 *NSEC_PER_SEC));
    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
           compelete(myUrl);
        }];
    }];
    
}

@end
